<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 创建全局变量
    let num = 0;
    // 创建一个自定义事件的对象；
    let myevent = new EventTarget();

    function fn1 (cb) {
      setTimeout(() => {
        console.log("fn1");
        cb && cb();  // 容错
        num++;
        // 触发自定义事件event1
        myevent.dispatchEvent(new CustomEvent("event" + num));
      }, 1000);
    }

    function fn2 (cb) {
      setTimeout(() => {
        console.log("fn2");
        cb && cb();
        num++;
        // 触发自定义事件event2
        myevent.dispatchEvent(new CustomEvent("event" + num));
      }, 1000);
    }

    function fn3 (cb) {
      setTimeout(() => {
        console.log("fn3");
        cb && cb();
        num++;
        // 触发自定义事件event3
        myevent.dispatchEvent(new CustomEvent("event" + num));
      }, 1000);
    }

    // 依次调用异步逻辑，会出现回调地狱
    // fn1(function () {
    //   fn2(function () {
    //     fn3(function () {
    //       console.log("执行完毕了");
    //     })
    //   })
    // })

    // 通过自定义事件来处理回调地狱
    fn1();
    myevent.addEventListener("event1", function () {
      console.log("event1函数执行完毕了");
      fn2();
    })
    myevent.addEventListener("event2", function () {
      console.log("event2函数执行完毕了");
      fn3();
    })
    myevent.addEventListener("event3", function () {
      console.log("所有异步函数执行完毕了");
    })
  </script>
</body>

</html>